package com.fansl.allround.common.core.validator;

import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author fansl
 * @Description: 邮箱验证
 * @date 2019/10/10 15:28
 */
public class EmailValidator extends ValidatorHandler<String> implements Validator<String> {
    private static String emailReg ="^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    public EmailValidator() {

    }

    @Override
    public boolean validate(ValidatorContext context, String s) {
        Pattern p  = Pattern.compile(emailReg);
        Matcher matcher = p.matcher(s);
        if (!matcher.matches()) {
            context.addError(ValidationError.create(String.format("邮箱格式不正确！"))
                    .setErrorCode(-1)
                    .setInvalidValue(s));
            return false;
        }
        return true;
    }
}
